<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>详情</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="realOrder.css" media="all">
</head>
<body>

<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list"
     style="padding: 0px 10px 0 10px;">
    <form class="layui-form" action="" lay-filter="component-form-element">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-lg12" style="float: none;">
                <!-- 头部表格 -->
                <table style="width: 100%;height: 50px;">
                    <tr style="color:#454c51;text-align: center;padding-bottom: 10px;;border-bottom:2px solid darkgray;">
                        <td style="width: 40%;">单据编号:<label id="orderNumber"></label></td>
                        <td style="width: 20%;"><label style="font-size:30px;">入住单</label></td>
                        <td style="width: 40%;">
                            <div class="layui-inline">
                                <label class="layui-form-label">住房日期</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <input type="text" class="layui-input" id="dataRan"
                                           readonly disabled>
                                </div>
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                共 <span id="totalDay">1</span> 晚
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div id="tableRes" class="table-overlay">
                <!-- 主表格，用于选择订单详情 -->
                <table id="dataTable" lay-filter="dataTable" class="layui-hide" style="margin-bottom: 0px;"></table>
                <!-- 统计信息表格 -->
                <table class="layui-table" style="margin-top: -10px;">
                    <thead>
                    <tr>
                        <th>
                            <div class="layui-form">
                                <label class="layui-form-label" style="width: 30px;">人数</label>
                                <div class="layui-inline">
                                    <input type="number" lay-verify="required|number" id="number" min="1" max="50"
                                           value="1" class="layui-input" style="width: 80px;">
                                </div>
                            </div>
                        </th>
                        <th>押金</th>
                        <th>
                            <div class="layui-form">
                                <div class="layui-form-item" style="margin-bottom: 0px;">
                                    <div class="layui-input-inline" style="width: 80px;">
                                        <input type="number" min="0" lay-verify="required|number"
                                               placeholder="金额" autocomplete="off"
                                               class="layui-input" id="cashMoney" value="100"
                                               onchange="comTotalMoney()">
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">元 / 间</div>
                                    <div class="layui-input-inline" style="width: 90px">
                                        <select lay-filter="cashPay" id="cashPay">
                                            <option value="0" selected>支付宝</option>
                                            <option value="1">现金</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item" style="margin-bottom: 0px;">
                                    <input type="button" onclick="payCashMoney()"
                                           class="layui-btn layui-btn-xs layui-btn-normal layui-btn-radius"
                                           style="width: 70px;"
                                           value="确认付款">
                                    <input type="button" onclick="checkPayCash()"
                                           class="layui-btn  layui-btn-danger layui-btn-xs layui-btn-radius"
                                           style="width: 40px;" value="刷新">
                                    <span id="payStatusCash" style="color: #ef5353">待付款</span>
                                </div>
                            </div>
                        </th>
                        <th rowspan="2">房费(元)：
                            <label id="totalPrice" class="capital" style="color: #ef5353;font-size:40px;">0.00</label>
                        </th>
                        <th>付款方式</th>
                        <th>
                            <div class="layui-form">
                                <div class="layui-form-item" style="width: 90px">
                                    <select lay-filter="totalPay" id="totalPay">
                                        <option value="0" selected>支付宝</option>
                                        <option value="1">现金</option>
                                    </select>
                                </div>
                                <div class="layui-form-item" style="margin-bottom: 0px;">
                                    <input type="button" onclick="payRoomMoney()"
                                           class="layui-btn layui-btn-xs layui-btn-normal layui-btn-radius"
                                           style="width: 70px;"
                                           value="确认付款">
                                    <input type="button" onclick="checkPayRoom()"
                                           class="layui-btn  layui-btn-danger layui-btn-xs layui-btn-radius"
                                           style="width: 40px;" value="刷新">
                                    <span id="payStatusRoom" style="color: #ef5353">待付款</span>
                                </div>
                            </div>
                        </th>
                    </tr>
                    </thead>
                </table>
                <fieldset class="layui-elem-field layui-field-title">
                    <legend>主客信息</legend>
                </fieldset>
                <table class="layui-table">
                    <thead>
                    <tr>
                        <td>主客姓名</td>
                        <td><input type="text" class="layui-input" id="name" lay-verify="required"/></td>
                        <td>身份证号：</td>
                        <td><input type="text" class="layui-input" id="idCard" lay-verify="required|identity"/></td>
                    </tr>
                    <tr>
                        <td>性别</td>
                        <td>
                            <div class="layui-input-block" style="margin-left: 0px;">
                                <input type="radio" name="sex" value="男" title="男" checked="">
                                <input type="radio" name="sex" value="女" title="女">
                            </div>
                        </td>
                        <td>手机号码：</td>
                        <td><input type="text" class="layui-input" id="phone" lay-verify="required|phone"/></td>
                    </tr>
                    <tr>
                        <td>备注信息</td>
                        <td colspan="3">
                            <input type="text" class="layui-input" id="remark"/>
                        </td>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div id="action" class="text-center">
            <button type="button" name="btnSave" class="layui-btn" lay-submit lay-filter="*">
                <i class="layui-icon layui-icon-ok-circle"></i>提交
            </button>
            <button type="reset" name="btnReset" class="layui-btn layui-btn-primary" onclick="closeThis()">取消
            </button>
        </div>
    </form>
</div>
<div id="mask" class="mask"></div>
<script src="../../layuiadmin/layui/layui.js"></script>
<script src="../../js/jquery-1.8.3.min.js"></script>
<script src="realOrder.js"></script>
<script>
    /* 基础配置 */
    //订单号
    var orderNumber = "";
    //房间信息
    var roomInfo = [];
    //表格行数
    var TableSize = 1;
    //押金订单号
    var orderN = "";
    //公开数据
    var outData;

    $("#dataRan").val(dateFormat(new Date()));


    //初始化列信息
    var rowInfo = {
        tempId: new Date().valueOf(),
        roomTypeId: 0,
        roomId: 0,
        oneDayPrice: 0,
        price: 0,
        name: '',
        idnumber: ''
    };

    /**
     * 配置本页信息
     */
    var wvInfo = {};
    $.extend(wvInfo, rowInfo);
    window.viewObj = {
        tbData: [wvInfo],
        typeData: [],
        renderSelectOptions: function (data, settings) {
            return dateToGroupSelect(data, settings)
        }
    };
    /**
     * 判断本页状态
     */
    if (parent.entityType == "toDetails") {
        $("#action").remove();
        $.ajax({
            url: parent.toDetailsURL,
            type: 'get',
            data: {"id": parent.entityId},
            dataType: 'json',
            async: false,//设置阻断
            success: function (data) {
                roomInfo = data.room;
                // console.log(data.customer);
                $("#orderNumber").html(data.order.ordernumber);
                $("#totalPrice").text(data.order.totalprice);
                $("#name").val(data.order.realname);
                if (data.order.sex == 0) {
                    $("input[name=sex][value='男']").prop("checked", "true");
                } else {
                    $("input[name=sex][value='女']").prop("checked", "true");
                }
                outData = data.order;
                $("#idCard").val(data.order.idnumber);
                $("#phone").val(data.order.phone);
                $("#remark").val(data.order.remark);
                $("#number").val(data.order.person_number);
                $("#cashPay").val(data.order.cashpay);
                $("#totalDay").val(data.order.days);
                $("#dataRan").val(dateFormat(data.order.real_in_time));
                $("#payStatusCash").text("已付款");
                $("#payStatusRoom").text("已付款");
                viewObj.tbData = data.data;
            },
            error: function () {
                parent.layer.alert("信息获取失败！");
                return;
            }
        });
    }

</script>
<script>
    /** layui配置 */
    layui.config({
        base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'table', 'laydate', 'layer'], function () {
            var $ = layui.$
                , form = layui.form
                , table = layui.table
                , laydate = layui.laydate
                , layer = layui.layer;
            //确定入住天数后查询该时间端内所有可预订的房间
            if (parent.entityType != "toDetails") {
                layer.prompt({
                    title: '请输入入住天数', closeBtn: 0, value: '1', maxlength: 2, formType: 0, btn2: function () {//这里就是你要的
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    },
                }, function (value, index) {
                    if (!/^\d+$/.test(value)) {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                        parent.layer.msg("请输入正确天数");
                    } else {
                        //下拉框初始化
                        $.ajax({
                            url: "/roomRealOrder/toAdd",
                            type: 'get',
                            data: {
                                "checkDate": dateFormat(new Date()),
                                "days": value,
                            },
                            dataType: 'json',
                            async: false,//设置阻断
                            success: function (data) {
                                orderNumber = data.orderNumber;
                                roomInfo = data.room;
                                $("#orderNumber").html(orderNumber);
                                // viewObj.tbData[0].price = 100;
                                // $(".layui-table-total").find("td[data-field=oneDayPrice] div").text("100");
                                tableIns.reload();
                            },
                            error: function () {
                                parent.layer.alert("信息获取失败！");
                                return;
                            }
                        });
                        $("#totalDay").text(value);

                        layer.close(index);
                    }
                });
            }

            //数据表格实例化
            var tbWidth = $("#toolbar").width() - 5;
            var layTableId = "layTable";
            var tableIns = table.render({
                elem: '#dataTable',
                id: layTableId,
                data: viewObj.tbData,
                // width: tbWidth,
                cellMinWidth: 60,
                totalRow: true,
                loading: true,
                even: false,
                cols: [[
                    {title: '序号', type: 'numbers', totalRowText: '合计', unresize: true},
                    {
                        field: 'roomId',
                        unresize: true,
                        title: '房间名称',
                        templet: function (d) {
                            var options = viewObj.renderSelectOptions(roomInfo, {
                                valueField: "id",
                                textField: "name",
                                selectedValue: d.roomId
                            });
                            return '<a lay-event="roomId"></a><select lay-search name="roomId" lay-filter="roomId">' +
                                '<option value="">请选择房间</option>' + options + '</select>';
                        }
                    },
                    {
                        field: 'oneDayPrice',
                        edit: 'number',
                        unresize: true,
                        title: '单日价格'
                    },
                    {field: 'price', unresize: true, title: '小计(元)', totalRow: true},
                    {field: 'name', title: '主客姓名', edit: 'text'},
                    {field: 'idnumber', title: '身份证号', edit: 'text'},
                    {
                        field: 'tempId', width: 80, unresize: true, title: '操作', templet: function (d) {
                            return '<a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i></a>'
                                + '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="' + d.tempId + '"><i class="layui-icon layui-icon-delete"></i></a>';
                        }
                    }
                ]],
                done: function (res, curr, count) {
                    // console.log(res.data);
                    viewObj.tbData = res.data;
                    //如果是查询则增加遮罩层
                    if (parent.entityType == "toDetails") {
                        $("[data-field='tempId']").css('display', 'none');
                        showMask();
                    }
                }
            });
            var initValue = "";
            var nowDate = new Date();
            var strDate = dateFormat(nowDate)
            initValue += dateFormat(nowDate);
            initValue += getNewData(strDate, 1);
            if (parent.entityType == "toDetails") {
                var dataran = dateFormat(outData.real_in_time);
                $("#dataRan").val(dataran);
                initValue = dateFormat(outData.real_in_time) + " - ";
                initValue += dateFormat(outData.real_out_time);
                var outDay = GetDateDiff(dateFormat(outData.real_out_time), dateFormat(outData.real_in_time));
                // console.log(day);
                $("#totalDay").text(outDay);
            }
            //验证表单
            form.on('submit(*)', function (data) {

                var oldData = table.cache[layTableId];
                for (var i = 0, row; i < oldData.length; i++) {
                    row = oldData[i];
                    if (!row.roomId) {
                        layer.msg("请检查房间是否选择完毕！", {icon: 5}); //提示
                        return;
                    }
                    if (!row.name) {
                        layer.msg("请输入主客姓名！", {icon: 5});
                        return;
                    }
                    if (!row.idnumber) {
                        layer.msg("请输入身份证号！", {icon: 5});
                        return;
                    }
                    if (!checkIDCard(row.idnumber)) {
                        layer.msg("请输入正确的身份证号", {icon: 5});
                        return;
                    }
                }
                var idnum = "";

                //验证身份证号是否有重复
                if (oldData.length > 1) {
                    for (var i = 0; i < oldData.length; i++) {
                        idnum = oldData[i].idnumber;
                        for (var j = 1; j < oldData.length; j++) {
                            if (idnum == oldData[i].idnumber) {
                                layer.msg("身份证号不能重复");
                                return;
                            }
                        }
                    }
                }

                if ($("#payStatusCash").text() != "已付款" || $("#payStatusRoom").text() != "已付款") {
                    layer.msg("请先支付!", {icon: 5});
                    return;
                }
                var load2 = layer.load(2, {shade: 0.1}); //0代表加载的风格，支持0-2
                //获取住房时间
                var inDay = $("#dataRan").val();
                var outDate = getNewData(inDay, $("#totalDay").text());
                //住房天数
                var dayNum = $("#totalDay").text();
                //获取人数
                var num = $("#number").val();
                //押金
                var cashMoney = $("#cashMoney").val();
                //押金收款方式
                var cashPay = $("#cashPay").val();
                //总价收款方式
                var totalPay = $("#totalPay").val();
                //主客姓名
                var name = $("#name").val();
                //身份证号
                var idcard = $("#idCard").val();
                //性别
                var sex = $('input[name="sex"]').filter(':checked').val();
                //电话
                var phone = $("#phone").val();
                var remark = $("#remark").val();
                var jsonInfo = {
                    "orderNumber": orderNumber,
                    "realname": name,
                    "phone": phone,
                    "realInTime": inDay,
                    "realOutTime": outDate,
                    "depositPrice": cashMoney,
                    "depositType": cashPay,
                    "days": dayNum,
                    "sex": sex,
                    "idNumber": idcard,
                    "remark": remark,
                    "totalPay": totalPay,
                    "num": num,
                    "table": table.cache[layTableId]
                }
                // --- 向后台传输数据 --
                var index = parent.layer.getFrameIndex(window.name);
                $.ajax({
                    url: "/roomRealOrder/add",
                    type: 'post',
                    data: JSON.stringify(jsonInfo),
                    contentType: "application/json;charset=UTF-8",
                    dataType: 'json',
                    async: false,//设置阻断
                    success: function (data) {
                        layer.close(load2);
                        parent.layer.msg(data.msg, {icon: data.icon, zIndex: layer.zIndex + 100});
                    }
                });
                layer.close(load2);
                parent.layui.table.reload('entityTable'); //重载表格
                parent.layer.close(index); //关闭该窗口

            });

            //用于存储事件的类型
            var activeType = "";
            //定义事件集合
            var active = {
                //修改行
                updateRow: function (obj) {
                    var oldData = table.cache[layTableId];
                    // console.log(oldData);
                    for (var i = 0, row; i < oldData.length; i++) {
                        row = oldData[i];
                        if (row.tempId == obj.tempId) {
                            $.extend(oldData[i], obj);
                            activeType = "";
                            break;
                        }
                    }

                    tableIns.reload({
                        data: oldData
                    });
                    comTotalMoney();
                },
                //删除一项
                removeEmptyTableCache: function () {
                    var oldData = table.cache[layTableId];
                    for (var i = 0, row; i < oldData.length; i++) {
                        row = oldData[i];
                        if (!row || !row.tempId) {
                            oldData.splice(i, 1);
                        }
                        continue;
                    }
                    tableIns.reload({
                        data: oldData
                    });
                    comTotalMoney()
                }
            };

            //修改单元格内容
            table.on('edit(dataTable)', function (obj) {
                var prices = parseFloat(obj.data.oneDayPrice);
                var tempRow = {};
                $.extend(tempRow, rowInfo);
                tempRow.tempId = obj.data.tempId;
                tempRow.roomId = obj.data.roomId;
                tempRow.roomTypeId = obj.data.roomTypeId;
                tempRow.oneDayPrice = parseFloat(obj.data.oneDayPrice).toFixed(2);
                tempRow.price = prices;
                tempRow.name = obj.data.name;
                tempRow.idnumber = obj.data.idnumber;

                //复制后边数据对象到前边的数据对象中
                $.extend(obj.data, tempRow);
                activeByType('updateRow', obj.data);
                tableIns.reload();
                comTotalMoney()
            });
            //监听select下拉选中事件
            form.on('select(roomId)', function (data) {
                //得到select原始DOM对象
                var elem = data.elem;
                $(elem).prev("a[lay-event='roomId']").trigger("click");
                tableIns.reload();
            });
            //监听工具条
            table.on('tool(dataTable)', function (obj) {
                var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
                // console.log(tr);
                switch (event) {
                    case "add":
                        var oldData = table.cache[layTableId];
                        // console.log(oldData);

                        var newRow = {};
                        $.extend(newRow, rowInfo);
                        newRow.tempId = new Date().valueOf();
                        oldData.push(newRow);
                        tableIns.reload({
                            data: oldData
                        });
                        TableSize += 1;
                        comTotalMoney();
                        break;
                    //修改房间下拉框时触发
                    case "roomId":
                        // console.log(data);
                        var select = tr.find("select[name='roomId']");
                        if (select) {
                            var newRow = {};
                            $.extend(newRow, rowInfo);
                            newRow.tempId = data.tempId;
                            newRow.roomId = select.val();

                            if (!newRow.roomId) {
                                layer.tips("请选择一个房间", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                            } else {
                                var oldData = table.cache[layTableId];
                                //如果选中的房间在该单中不存在，则可以添加，已存在则提示并拦截添加。
                                var temp = true;
                                for (var s in oldData) {
                                    if (oldData[s].roomId == newRow.roomId) {
                                        layer.tips("本订单已存在该房间", select.next('.layui-form-select'), {tips: [3, '#FF5722']});
                                        newRow.roomId = "";
                                        temp = false;
                                    }
                                }
                                if (temp) {
                                    for (var i in roomInfo) {
                                        //把房间id和json里的对比
                                        if (JSON.stringify(roomInfo[i].id) == newRow.roomId) {
                                            newRow.roomTypeId = roomInfo[i].rtid;
                                            newRow.oneDayPrice = roomInfo[i].price.toFixed(2);
                                            newRow.price = roomInfo[i].price.toFixed(2);
                                        }
                                    }
                                }
                            }
                            $.extend(obj.data, newRow);
                            activeType = "roomId";
                            //更新行记录对象
                            activeByType('updateRow', obj.data);

                        }
                        break;
                    //点击删除触发的事件
                    case "del":
                        var str = tr.selector.substring(tr.selector.indexOf('="') + 2, tr.selector.indexOf('"]'));
                        if (str == "0") {
                            layer.msg("首条数据不可删除！");
                            break;
                        }
                        layer.confirm('真的删除行么？', function (index) {
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                            activeByType('removeEmptyTableCache');
                        });
                        TableSize -= 1;
                        comTotalMoney()
                        break;
                }
            });
            //激活事件
            var activeByType = function (type, arg) {
                if (arguments.length === 2) {
                    active[type] ? active[type].call(this, arg) : '';
                } else {
                    active[type] ? active[type].call(this) : '';
                }
            };
            //注册按钮事件
            $('.layui-btn[data-type]').on('click', function () {
                var type = $(this).data('type');
                activeByType(type);
            });
        }
    )
</script>
</body>
</html>